//
//  QLNetWorking.m
//  青旅OA
//
//  Created by qlwl on 16/4/19.
//  Copyright © 2016年 qlwl. All rights reserved.
//

#import "QLNetWorking.h"
#import "NSDate+time.h"

@implementation QLNetWorking

#pragma mark 网络状态的监听

+ (void)startMonitoring
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
}

+ (void)stopMonitoring
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager stopMonitoring];
}

+ (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (block) {
            block(status);
            /* switch (status) {
             case AFNetworkReachabilityStatusUnknown:
             NSLog(@"未知");
             break;
             case AFNetworkReachabilityStatusNotReachable:
             NSLog(@"没有网络");
             break;
             case AFNetworkReachabilityStatusReachableViaWWAN:
             NSLog(@"3G|4G");
             break;
             case AFNetworkReachabilityStatusReachableViaWiFi:
             NSLog(@"WiFi");
             break;
             default:
             break;
             }*/
        }
    }];
}
//是否可以链接网络
+(BOOL)canLinkNetWorking
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    return manager.reachable;
}

#pragma mark 数据请求
+ (void)getJSONWithUrl:(NSString *)urlStr parameters:(id)parameters isJosnRequest:(BOOL)isJosn progress:(void(^)(NSProgress *downloadProgress))progress success:(void (^)(id result))success fail:(void (^)(NSError *error))fail
{
    AFHTTPSessionManager *manager=[[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:urlStr]];
    if (isJosn) {
        //设置请求格式，如果是json请求各式，设置如果不是，系统默认
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
    }
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html",@"text/javascript", nil];
    //讲字符串转换成字典
    [manager.requestSerializer setTimeoutInterval:8];
    parameters=[self getPostDictWithPostStr:parameters];
    [manager GET:urlStr parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        if (progress) {
            progress(downloadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        id result = nil;
        if ([responseObject isKindOfClass:[NSData class]]) {
            result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        }else{
            result = responseObject;
        }
        
        if (success) {
            success(result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail(error);
        }
    }];
}
+ (void)getJSONWithUrl:(NSString *)urlStr parameters:(id)parameters success:(void (^)(id result))success fail:(void (^)(NSError *error))fail
{
    [self getJSONWithUrl:urlStr parameters:parameters isJosnRequest:NO progress:nil success:^(id result) {
        if (success) {
            success(result);
        }
    } fail:^(NSError *error) {
        if (fail) {
            fail(error);
        }
    }];
}
//progress:(void(^)(NSProgress *downloadProgress))progress
+ (void)postJSONWithUrl:(NSString *)urlStr parameters:(id)parameters isJosnRequest:(BOOL)isJosn rogress:(void(^)(NSProgress *downloadProgress))progress success:(void (^)(id result))success fail:(void (^)(NSError *error))fail
{
    AFHTTPSessionManager *manager=[[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:urlStr]];
    if (isJosn) {
        //设置请求格式，如果是json请求各式，设置如果不是，系统默认
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
    }
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html",@"text/javascript", nil];
    [manager.requestSerializer setTimeoutInterval:16];
    //讲字符串转换成字典
    parameters=[self getPostDictWithPostStr:parameters];
    QLLog(@"%@",[self getPostJsonWithDict:parameters]);
    
    [manager POST:urlStr parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress) {
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id result=responseObject;
        if (success) {
            success(result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail(error);
        }
    }];
}
+ (void)postJSONWithUrl:(NSString *)urlStr parameters:(id)parameters success:(void (^)(id result))success fail:(void (^)(NSError *error))fail
{
    [self postJSONWithUrl:urlStr parameters:parameters isJosnRequest:NO rogress:nil success:^(id result) {
        if (success) {
            success(result);
        }
    } fail:^(NSError *error) {
        if (fail) {
            fail(error);
        }
    }];
}
+(void)upImaWithURL:(NSString *)urlStr parameters:(id)parameters fieldNames:(NSArray *)files andImaNames:(NSArray *)imaNames mimeType:(NSString *)mimeType andImas:(NSArray *)imasArray progress:(void(^)(NSProgress *uploadProgress))progress success:(void (^)(id result))success fail:(void (^)(NSError *error))fail
{
    [self upFileWithURL:urlStr parameters:parameters isJosnRequest:NO constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        for (int i=0 ;i<imasArray.count;i++) {
            UIImage *ima = imasArray[i];
            NSData *imaData=UIImageJPEGRepresentation(ima, 0.5);
            NSString *file = files.count>i?files[i]:[files lastObject];
            NSString *imaName = imaNames.count>i?imaNames[i]:[[[NSDate date] getTimeSp] stringByAppendingString:@".png"];
            
            [formData appendPartWithFileData:imaData name:file fileName:imaName mimeType:mimeType];
        }
    } progress:^(NSProgress *uploadProgress) {
        if (progress) {
            progress(uploadProgress);
        }
    } success:^(id result) {
        if (success) {
            success(result);
        }
    } fail:^(NSError *error) {
        if (fail) {
            fail(error);
        }
    }];

}
+(void)upImaWithURL:(NSString *)urlStr parameters:(id)parameters fieldName:(NSString *)file andImas:(NSArray *)imasArray progress:(void(^)(NSProgress *uploadProgress))progress success:(void (^)(id result))success fail:(void (^)(NSError *error))fail
{
    [self upImaWithURL:urlStr parameters:parameters fieldNames:[NSArray arrayWithObjects:file, nil] andImaNames:nil mimeType:@"image/jpeg" andImas:imasArray progress:^(NSProgress *uploadProgress) {
        if (progress) {
            progress(uploadProgress);
        }
    } success:^(id result) {
        if (success) {
            success(result);
        }
    } fail:^(NSError *error) {
        if (fail) {
            fail(error);
        }
    }];
}

+(void)upImaWithURL:(NSString *)urlStr parameters:(id)parameters fieldName:(NSString *)file andImas:(NSArray *)imasArray success:(void (^)(id result))success fail:(void (^)(NSError *error))fail
{
    [self upImaWithURL:urlStr parameters:parameters fieldName:file andImas:imasArray progress:nil success:^(id result) {
        if (success) {
            success(result);
        }
    } fail:^(NSError *error) {
        if (fail) {
            fail(error);
        }
    }];
}

+(void)upFileWithURL:(NSString *)urlStr parameters:(id)parameters isJosnRequest:(BOOL)isJosn constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block progress:(void(^)(NSProgress *uploadProgress))progress success:(void (^)(id result))success fail:(void (^)(NSError *error))fail
{
    AFHTTPSessionManager *manager=[[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:urlStr]];
    if (isJosn) {
        //设置请求格式，如果是json请求各式，设置如果不是，系统默认
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
    }
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html",@"text/javascript", nil];
    [manager.requestSerializer setTimeoutInterval:16];
    //讲字符串转换成字典
    parameters=[self getPostDictWithPostStr:parameters];
    [manager POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (block) {
            block(formData);
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress) {
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail(error);
        }
    }];
}
+(void)upFileWithURL:(NSString *)urlStr parameters:(id)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block success:(void (^)(id result))success fail:(void (^)(NSError *error))fail
{
    [self upFileWithURL:urlStr parameters:parameters isJosnRequest:NO constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (block) {
            block(formData);
        }
    } progress:nil success:^(id result) {
        if (success) {
            success(result);
        }
    } fail:^(NSError *error) {
        if (fail) {
            fail(error);
        }
    }];
}

#pragma mark 讲参数字符串转换成参数字典
//讲字符串参数转成数组   每个参数之间用&分割，
+ (id) getPostDictWithPostStr:(id)postStr
{
    if (![postStr isKindOfClass:[NSString class]]) {
        NSLog(@"%@",postStr);
        return postStr;
    }
    NSArray *array=[postStr componentsSeparatedByString:ParameterSegmentationCharacter];
    NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
    for (NSString *subStr in array) {
        NSArray *subArray=[subStr componentsSeparatedByString:KeyValueSegmentationCharacter];
        if ((int)subArray.count!=2) {
            continue;
        }
        NSString *lastStr=[subArray lastObject];
        NSString *firstStr=[subArray firstObject];
        if ((firstStr!=nil)&&(lastStr!=nil)&&(![lastStr isEqualToString:@"(null)"])) {
            [dict setObject:[subArray lastObject] forKey:[subArray firstObject]];
        }
    }
    NSLog(@"%@",dict);
    return dict;//[self getPostJsonWithDict:dict];
}
+(id) getPostJsonWithDict:(NSDictionary *)dict
{
    if (![dict isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}


//判断返回数据是否正确
+(BOOL)sucess:(NSDictionary *)result
{
    if ([self sucess:[result objectForKey:@"MobileHead"] and:@"Code" EqualToString:@"AC_001"]) {
        return YES;
    }
    return NO;
}

+(BOOL)sucess:(NSDictionary *)result and:(NSString *)key EqualToString:(NSString *)string
{
    NSString * resultCode = [NSString stringWithFormat:@"%@",[result objectForKey:key]];
    return [resultCode isEqualToString:string];
    /*MobileHead = {
     Message = 成功;
     Code = BE_002;
     }*/
}
+ (NSString *)resultMessage:(NSDictionary *)result
{
    return [[result objectForKey:@"MobileHead"] objectForKey:@"Message"];
}
@end
